package com.dingreading.cloud.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 微信公众号工具
 */
public class WxGzhUtil {

    private static Logger logger = LoggerFactory.getLogger(WxGzhUtil.class);

    /**
     * 获取微信关注accessToken
     * @return
     */
    public static String getWxAccessToken() {
        String tokenData = HttpUtils.get("https://wx.dingreading.com/?r=wx/member/getwxtoken");
        if (StringUtils.isNotBlank(tokenData)) {
            JSONObject jsonObject = JSONObject.parseObject(tokenData);
            Integer st = jsonObject.getInteger("st");
            String msg = jsonObject.getString("msg");
            String data = jsonObject.getString("data");
            if (st.equals(0)) {
                // 处理微信消息提醒
                return data;
            }
        }
        return "";
    }

    /**
     * 发送模板消息
     */
    public static JSONObject sendTemplate(String data, String accessToken) {
        JSONObject object = null;
        try {
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
            String result = HttpUtils.post(requestUrl, data);
            if (StringUtils.isNotBlank(result)) {
                object = JSONObject.parseObject(result);
                Integer errcode = object.getInteger("errcode");
                if (errcode == null || errcode != 0) {
                    logger.error("发送模板消息，失败：" + result);
                }
            } else {
                logger.error("发送模板消息，失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

}
